import _ from 'lodash'

function toHump(name) {
  return name.replace(/\_(\w)/g, function (all, letter) {
    return letter.toUpperCase()
  })
}

const toJS = obj => {
  if (!_.isObjectLike(obj) && !_.isArray(obj)) {
    return obj
  }

  if (_.isArray(obj)) {
    return [..._.map(obj, o => toJS(o))]
  }

  return { ...obj }
}

/**
 * 递归转为camel case
 * @param originObj
 * @returns {*}
 */
const camelCaseObject = originObj => {
  if (!_.isArray(originObj) && !_.isObjectLike(originObj)) {
    return originObj
  }

  if (_.isArray(originObj)) {
    return _.map(originObj, item => {
      if (_.isObjectLike(item)) {
        return camelCaseObject(item)
      }

      return item
    })
  }

  const obj = { ...originObj }
  const result = {}
  for (const key in obj) {
    let value = obj[key]
    if (_.isObjectLike(obj[key])) {
      value = camelCaseObject(value)
    }

    result[toHump(key)] = value
  }

  return result
}

/**
 * 递归转为snake case
 * @param originObj
 * @returns {*}
 */
const snakeCaseObject = originObj => {
  if (!_.isArray(originObj) && !_.isObjectLike(originObj)) {
    return originObj
  }

  if (_.isArrayLike(originObj)) {
    return _.map(originObj, item => {
      if (_.isObjectLike(item)) {
        return snakeCaseObject(item)
      }

      return item
    })
  }

  const obj = { ...originObj }
  const result = {}
  for (const key in obj) {
    let value = obj[key]
    if (_.isObjectLike(obj[key])) {
      value = snakeCaseObject(value)
    }

    result[_.snakeCase(key)] = value
  }

  return result
}

/**
 * 非递归转为snake case
 * @param obj
 * @returns {Object|*}
 */
const snakeCase = obj => {
  return _.mapKeys(obj, (v, k) => _.snakeCase(k))
}

/**
 * 非递归转为camel case
 * @param obj
 * @returns {Object|*}
 */
const camelCase = obj => _.mapKeys(obj, (v, k) => toHump(k))

export { toJS, snakeCase, camelCase, snakeCaseObject, camelCaseObject }
